import BASE_URL from "@/config/env.js"
const request = (options) => {
  return new Promise((resolve, reject) => {
    const header = {
      "Content-Type": "application/json",
    }
    const token = uni.getStorageSync("token")
    if (token) {
      header["Authorization"] = "Bearer " + token
    } else {
      header.istoken = "false"
    }
    if (!options.isHide) {
      uni.showLoading({
        title: "加载中",
        mask: true,
      })
    }
    uni.request({
      url: BASE_URL + options.url, //接收请求的API
      method: options.method || "get", //接收请求的方式,如果不传默认为GET
      data: options.data || {}, //接收请求的data,不传默认为空
      header: header, //接收请求的header
      success(res) {
        uni.hideLoading()
        if (res.data.code === 200) {
          resolve(res.data) // 使用resolve将数据传递出去
        } else {
          if (!options.isHide) {
            uni.hideLoading()
            wx.showToast({
              title: "请求失败",
              icon: "none",
            })
          }
          resolve(res.data)
        }
      },
      fail: (err) => {
        if (!options.isHide) {
          uni.hideLoading()
          wx.showToast({
            title: "请求失败",
            icon: "none",
          })
        }
        reject(err)
      },
    })
  })
}

export default request
